<?php
class MY_Controller Extends CI_Controller
{
	
	var $school_name = FALSE;
	var $school_address = FALSE;
	var $school_telephone = FALSE;
	var $school_email = FALSE;
	var $school_tag_name = FALSE;
	var $current_grading_period = FALSE; // returns id of current grading period
	var $current_school_year = FALSE; // returns id of current school year
	var $schoolyear_date = FALSE; // returns school year format of 0000 - 0000
	var $gperiods_current; // Returns the gp_desc of current grading period
	var $session_user;
	var $disable_browser_cache = FALSE;
	var $other_assets = array();
	
	protected $enrollment_link;
	protected $student_link;
	protected $accounting_link;
	
	protected $pagnate_config = array();
	protected $layout_view = 'application';
    protected $content_view ='';
    protected $view_data = array();
	protected $page_title = 'School System';
	protected $use_bootstrap3 = false;
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('M_system_check','msc');
		if($this->msc->check() == TRUE)
		{
			// initializes no cache function		
			$this->disable_browser_cache($this->disable_browser_cache);
			// CI built in profiler
			$this->output->enable_profiler(FALSE);
			//load school name and other credentials like school year and school grading period
			$this->load->model(array('M_school_settings','M_gperiods','M_school_years','M_user_tool_tip'));
			$this->current_grading_period 	= $this->M_gperiods->get_id_of_current_gperiod();
			$this->current_school_year		= $this->M_school_years->get_id_of_current_sy();
			$this->system_school_year		= $this->M_school_years->get_school_year_set();
			$this->schoolyear_date			= $this->M_school_years->get_current_sy_format();
			$this->schoolyear_desc			= $this->M_school_years->get_current_sy_desc();
			$this->gperiods_current			= $this->M_gperiods->get_current_gperiods_value('gp_desc');
			$this->session_user 			= $this->session->userdata('userType');
			$this->tip 						= $this->M_user_tool_tip->get_tool_tip($this->session->userdata('userid'));
			// checks if schoolyear and grading period is set, creates and error if none
			$this->_force_set_settings();
			
			$query = $this->M_school_settings->get_all_school_setting();
			
			if(!empty($query))
			{
				$this->school_name = $query->school_name;
				$this->school_address = $query->school_address;
				$this->school_telephone = $query->school_telephone;
				$this->school_email = $query->school_email;
			}
		}else{
			$message = implode(',',$this->msc->get_missing_tables());
			log_message('error','Missing database table(s) ( '.$message.' )');
			show_error('Database error has occurred. Check error log for more information.');
		}
		
		$this->view_data['use_bootstrap3'] = $this->use_bootstrap3;
		$this->available_sy = $this->M_school_years->get_available_sy();

		/** For Setting School Year Dynamically **/
		if( $this->session->userdata('logged_in') == TRUE
			&& $this->router->class != "change"
			&& $this->router->class != "set_user_school_year"){ $this->session->set_userdata('refered_from', uri_string()); }
	}
	
	public function _output($output)
    {
		//elapsed_time and memory_usage to show in views
		$this->view_data['elapsed_time'] = $this->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
		$this->view_data['memory_usage'] = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
        $this->view_data['title'] = @$this->page_title;
  	   if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
        
        $yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
        
        if($this->layout_view)
		{	
            echo $this->load->view('layouts/' . $this->layout_view, array('yield' => $yield), TRUE);
			echo $output;
		}
	}
	
	/**
	* function for formatting and redirecting message, using flashmessage
	* @param string $type e,s,n,p 
	* @param string $message the message you want to be sent 
	* @param string $redirect the url segment i.e controller/method 
	* @param string $var_name uses a different name for flashdata 
	* @return string formatted string with css and html
	*/
	public function _msg($type = FALSE,$message = FALSE,$redirect = FALSE,$var_name = 'system_message')
	{
		$type = strtolower($type);
		switch($type)
		{
		 	case $type === 'e':
				$template = "<div data-alert class='alert-box alert'><i class='icon-exclamation-sign'></i> ".$message."</div>";
			break;
			case $type === 's':
				$template = "<div data-alert class='alert-box success'><i class='icon-ok'></i> ".$message."</div>";
			break;
			case $type === 'n':
				$template = "<div class='alert-box'><i class='icon-info-sign'></i> ".$message."</div>";
			break;
			case $type === 'p':
				$template = $message;
			break;
			case $type === FALSE;
				$template = $message;
			break;
		}
		
		if($type AND $message AND $redirect)
		{
			$this->session->set_flashdata($var_name,$template);
			redirect($redirect);
		}elseif($type AND $message AND $redirect == FALSE){
			return $template;
		}
		
		if($redirect == FALSE AND $message == FALSE AND $redirect == FALSE)
		{
			return $this->session->flashdata($var_name);
		}
	}
	
	public function _mdf($x)
	{
		return date('Y-m-d',strtotime($x));
	}
	
	
	protected function _force_set_settings()
	{
		if($this->current_grading_period == FALSE)
		{
			$this->view_data['global_message'] = $this->_msg('n','Grading Period not yet set. Please create and set a Grading Period.');
		}
		
		if($this->current_school_year == FALSE)
		{
			$this->view_data['global_message'] = $this->_msg('n','School Year not yet set. Please create and set a School Year.');
		}
	}
	
	private function disable_browser_cache($x)
	{
		if($x == TRUE)
		{
			header("Last-Modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT"); // Date in the past 
			header("Expires: " . gmdate( "D, j M Y H:i:s", time() ) . " GMT"); // always modified 
			header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 
			header("Cache-Control: post-check=0, pre-check=0", FALSE); 
			header("Pragma: no-cache");
		}
	}
	
	protected function _init_pagnate_config()
	{
		// $this->pagnate_config['use_page_numbers'] = FALSE;
		// $this->pagnate_config['display_pages'] = FALSE;
		$this->pagnate_config['full_tag_open'] = '<div style="margin-top:1px;margin-bottom:1px;" class="pagination pagination-centered"><ul>';
		$this->pagnate_config['full_tag_close'] = '</ul></div>';
		
		$this->pagnate_config['first_link'] = '<i class="icon-fast-backward"></i>';
		$this->pagnate_config['last_link'] = '<i class="icon-fast-forward"></i>';
		$this->pagnate_config['next_link'] = '<i class="icon-step-forward"></i>';
		$this->pagnate_config['prev_link'] = '<i class="icon-step-backward"></i>';
		
		$this->pagnate_config['first_tag_open'] = '<li>';
		$this->pagnate_config['first_tag_close'] = '</li>';
		
		$this->pagnate_config['last_tag_open'] = '<li>';
		$this->pagnate_config['last_tag_close'] = '</li>';
		
		$this->pagnate_config['next_tag_open'] = '<li>';
		$this->pagnate_config['next_tag_close'] = '</li>';
		
		$this->pagnate_config['prev_tag_open'] = '<li>';
		$this->pagnate_config['prev_tag_close'] = '</li>';
		
		$this->pagnate_config['cur_tag_open'] = '<li class="disabled"><a style="color:#f00;fontweight:bold;" href="#">';
		$this->pagnate_config['cur_tag_close'] = '</a></li>';
		
		$this->pagnate_config['num_tag_open'] = '<li>';
		$this->pagnate_config['num_tag_close'] = '</li>';
	}
	
	protected function _set_config_items()
	{
		$sql = 'SELECT * FROM backend_settings';
		$query = $this->db->query($sql);
		$data= $query->num_rows() >=1 ? $query->row() : FALSE;
	
		if($data !== FALSE)
		{
			$this->enrollment_link = $data->enrollment_link;
			$this->student_link =$data->student_link;
			$this->accounting_link = $data->accounting_link;
		}
	}
	

	
	protected function _enc($x)
	{
		$this->load->library('hs');
		return $this->hs->encrypt($x);
	}
	
	protected function _dec($x)
	{
		$this->load->library('hs');
		$id = $this->hs->decrypt($x);
		return intval($id[0]);
	}
	
	protected function __ssget($type = FALSE)
	{
		$this->load->model('M_school_settings','asdf');
		return $this->asdf->test($type);
	}
	
	protected function _accronymizer($string = FALSE)
	{
		if($string !== FALSE)
		{
			$clean_string = htmlspecialchars(strip_tags($string));
			$number_of_words = str_word_count($clean_string,1);
			
			$accronym = array_map(function($x){
				if(strlen($x) > 1){return $x[0];}
			},$number_of_words);
			return strtoupper(implode('',$accronym));
		}else{
			return NULL;
		}
	}
	
	protected function _check_time($time = '')
	{
		return date('Y-m-d',$time) == date('Y-m-d');
	}

	protected function logger($filename = '',$message,$time = 'H:i:s A')
	{
		$path = './system_logs/';
		$ip = $this->input->ip_address();
		if(file_exists($path))
		{
			$this->load->library('user_agent');
			$this->load->helper('file');

			$browser_data = 'BRWSR:'.$this->agent->browser().'|OS:'.$this->agent->platform();


			$filename = $filename.'_'.date('m_d_Y');
			
			write_file($path.$filename.'.txt', '['.date($time).'|'.$browser_data.'|'.$ip.'] '.$message."\n",'a+');	
		
		}
	}
}